import {useModel} from '@@/exports';
import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {EditableProTable} from '@ant-design/pro-components';
import {Button, Form, message, Popconfirm, Select, Space} from 'antd';
import React, {useState} from 'react';
import {
  deleteMonthlyPlanningNumberUsingDELETE,
  editMonthlyPlanningNumberUsingPUT,
  listMonthlyPlanningNumberDTOUsingGET
} from "@/services/model/monthlyPlanningController";
import './LeftTable.css';
import unique from "fork-ts-checker-webpack-plugin/lib/utils/array/unique";
import AddModel from "@/pages/MonthlyPlanning/components/AddModel";

type LeftTableProps = {
  onClickRow: (row: API.MonthlyPlanningNumberDTO) => void;
  actionRef: React.MutableRefObject<ActionType | undefined>;
};
let dataSource: API.MonthlyPlanningNumberDTO[] = [];
const LeftTable: React.FC<LeftTableProps> = (props: LeftTableProps) => {
  const {initialState} = useModel('@@initialState');

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [filterDataSource, setFilterDataSource] = useState<readonly API.MonthlyPlanningNumberDTO[]>([]);
  const [rowId, setRowId] = useState('');
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [form] = Form.useForm();

  const initListMonthlyPlanningNumber = async () => {
    const result = await listMonthlyPlanningNumberDTOUsingGET({
      commitUserId: initialState?.currentUser?.id
    });
    if (result.data) {
      dataSource = result.data;
    }
    return {
      data: result.data,
      total: 3,
      success: true,
    };
  };
  const onDelete = async (record: API.MonthlyPlanningNumberDTO) => {
    const result = await deleteMonthlyPlanningNumberUsingDELETE({
      productionLineCode: record.productionLineCode,
      year: record.year,
      month: record.month,
      currentUserId: initialState?.currentUser?.id,
    });
    if (result.code === 0 && result.data) {
      message.success('删除成功');
      props.actionRef.current?.reload();
    } else {
      message.error(result.message);
    }
  };
  const onEdit = async (record: API.MonthlyPlanningNumberDTO) => {
    const currentUserId = initialState?.currentUser?.id;
    const newMonthlyPlanningNumber: API.EditMonthlyPlanningNumberQuery = {
      productionLineCode: record.productionLineCode,
      planningNumber: record.planningNumber,
      year: record.year,
      month: record.month,
      currentUserId,
    };
    const result = await editMonthlyPlanningNumberUsingPUT(newMonthlyPlanningNumber);
    if (result.code === 0 && result.data) {
      message.success('修改成功');
    } else {
      message.error(result.message);
    }
    props.actionRef.current?.reload();
  };

  const columns: ProColumns<API.MonthlyPlanningNumberDTO>[] = [
    {
      title: '产线编码',
      key: 'productionLineCode',
      dataIndex: 'productionLineCode',
      valueType: 'text',
      editable: false,
    },
    {
      title: '产线名称',
      key: 'productionLineName',
      dataIndex: 'productionLineName',
      valueType: 'text',
      editable: false,
    },
    {
      title: '年',
      key: 'year',
      dataIndex: 'year',
      valueType: 'digit',
      width: 50,
      editable: false,
      render: (text, record) => {
        return record.year && record.year.toString();
      }
    },
    {
      title: '月',
      key: 'month',
      dataIndex: 'month',
      valueType: 'digit',
      width: 50,
      editable: false,
    },
    {
      title: '产线规划人数',
      key: 'planningNumber',
      dataIndex: 'planningNumber',
      valueType: 'digit',
      width: 100,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={(e) => {
            e.stopPropagation()
            form.resetFields();
            action?.startEditable?.("" + record.productionLineCode + record.year + record.month);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key={'onDelete'}
          title="你想要删除这个产线配置吗"
          onConfirm={() => onDelete(record)}
          okText="Yes"
          cancelText="No"
        >
          <a key="deletable" onClick={(e) => e.stopPropagation()}>删除</a>
        </Popconfirm>,
      ],
    },
  ];
  const setRowClassName = (record: API.MonthlyPlanningNumberDTO) => {
    return ("" + record.productionLineCode + record?.year + record.month) === rowId ? 'clickRowStyl' : '';
  }
  return (
    <>
      <div style={{display: "flex", justifyContent: "space-between", margin: "10px 10px 0px 10px"}}>
        <Space>
          <Button
            type="primary"
            onClick={() => {
              setIsModalOpen(true)
            }}
            icon={<PlusOutlined/>}
          >
            新增 月度规划信息
          </Button>
        </Space>
        <Select
          allowClear
          popupMatchSelectWidth={200}
          onChange={(value) => {
            if (value) {
              const temp: API.MonthlyPlanningNumberDTO[] = [];
              dataSource.forEach(item => {
                if (item.productionLineCode === value) {
                  temp.push(item);
                }
              })
              setFilterDataSource(temp);
            } else {
              setFilterDataSource(dataSource)
            }
          }}
          placeholder={"选择 产线"}
          style={{width: 150}}
          options={unique(dataSource.map(item => item.productionLineCode)).map(item => {
            return {label: item, value: item}
          })}
        />
      </div>

      <EditableProTable<API.MonthlyPlanningNumberDTO>
        rowKey={(record) => {
          return "" + record.productionLineCode + record?.year + record.month;
        }}
        onRow={(record) => {
          return {
            onClick: () => {
              props.onClickRow(record);
              setRowId("" + record.productionLineCode + record?.year + record.month);
            },
          };
        }}
        scroll={{y: 'calc(100vh - 205px)'}}
        actionRef={props.actionRef}
        headerTitle="产线表"
        rowClassName={setRowClassName}
        recordCreatorProps={false}
        columns={columns}
        request={() => initListMonthlyPlanningNumber()}
        value={filterDataSource}
        onChange={(value) => {
          setFilterDataSource(value);
        }}
        editable={{
          form,
          editableKeys,
          onSave: async (key, row: any) => {
            await onEdit(row);
          },
          onChange: setEditableRowKeys,
          actionRender: (row, config, dom) => [dom.save, dom.cancel],
        }}
      />
      <AddModel
        isModalOpen={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
        actionRef={props.actionRef}/>
    </>
  );
};

export default LeftTable;
